﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Portal.Cms.Bussiness;
using Portal.Web.Utility;
using Portal.Cms.Model;
using Portal.Utility;
using Portal.Web.Model;
using Portal.Core;
using dtSearch32Lib;
using DocumentSearchServiceModel;
using DocumentSearch32Lib;
using Portal.Systems.Model;
using Portal.Workflow.Bussiness;
using Portal.Cms.Utility;
using System.Data;
using System.Collections.ObjectModel;

namespace Portal.Cms.Render
{
    public class UpdateCmsDocumentDataRenderBll
    {
        static string GetPlugInJavascript(string SiteId)
        {
            string ScriptText =
                   "<script language=javascript>\r\n" +

                   "</script>\r\n";
            return ScriptText;
        }


        public static AjaxOut Draw(string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                string GroupDataId = (string)WebEnvironments.Request(SiteId, "gid");
                string CmsDataId = (string)WebEnvironments.Request(SiteId, "CmsDataId");
                string BackUrl = (string)WebEnvironments.Request(SiteId, "Back");
                if (string.IsNullOrEmpty(BackUrl))
                {
                    BackUrl = "DocumentInputData.aspx?gid=" + GroupDataId;
                }
                //kiem tra xem co trong quy trinh khong da
                string Html =
                   GetPlugInJavascript(SiteId) +
                   DrawUpdateForm(SiteId, GroupDataId, CmsDataId, BackUrl).HtmlContent;

                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }

            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut DrawUpdateForm(string SiteId, string GroupDataId, string CmsDataId, string BackUrl)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                GroupDataCls OGroupData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateGroupDataModel(null, SiteId, GroupDataId);
                CmsDataCls OCmsData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateCmsDataModel(null, SiteId, CmsDataId);
                if (OGroupData == null) throw new Exception("Tham số truy cập không hợp lệ. Nhóm tin không tìm thấy!");
                if (OCmsData == null) throw new Exception("Tham số truy cập không hợp lệ. Bài viết không tìm thấy hoặc đã được xóa!");

                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                bool HasStarted = WorkflowUtilities.CheckHasStartWorkflow(SiteId, CmsDataId);
                if (HasStarted == false)
                {
                    //neu chua nam trong quy trinh thi kiem tra binh thuong
                    SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, GroupDataPermission.StaticId, GroupDataPermission.funcAccess, GroupDataId, WebSessionUtility.GetCurrentLoginUser().UserId, true);
                }
                else
                {
                    //neu nam trong quy trinh
                    string WorkflowDefId = OCmsData.WorkflowDefId;
                    if (!string.IsNullOrEmpty(WorkflowDefId))//co quy trinh
                    {
                        Portal.Workflow.Bussiness.WorkflowBll.GetWorkflowCls
                              OWorkFlowInfo = WorkflowBll.GetWorkflowActionInfo(OSiteParam.ConnectionString, WorkflowDefId, CmsDataId);
                        //lay thong tin
                        if (OWorkFlowInfo == null)
                        {
                            //neu khong duoc chuyen thi la chua den luot minh
                            throw new Exception("Bài viết đang nằm trong quy trình và bạn không có quyền sửa");
                        }
                        else
                        {
                            if (OWorkFlowInfo.IsViewer)
                            {
                                //da duoc xu ly
                                throw new Exception("Bài viết  trong quy trình và đã được người khác lấy về xử lý bạn không có quyền sửa");
                            }
                        }
                    }
                    else
                    {
                        SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, GroupDataPermission.StaticId, GroupDataPermission.funcAccess, GroupDataId, WebSessionUtility.GetCurrentLoginUser().UserId, true);
                    }
                }

                //string BackScript = "javascript:window.open('DocumentInputData.aspx?gid=" + OGroupData.GroupDataId + "','_self');";
                string BackScript = "javascript:window.history.back();";
                //if (!string.IsNullOrEmpty(BackUrl))
                //{
                //    BackScript = "javascript:window.open('" + BackUrl + "','_self');";
                //}


                string UploadHandler = "CmsUploadHandler.ashx";
                if (OGroupData.frkDataTypeId.Equals("document"))
                {
                    UploadHandler = "CmsUploadAttachFileHandler.ashx";
                }
            
                string Html =
                     "<script language=javascript>\r\n " +

                    "  function ProcessExpandCollapse(Id)\r\n" +
                    "  {\r\n" +
                    "     if(document.getElementById(Id).className=='Collapsed')\r\n" +
                    "     {\r\n" +
                    "         document.getElementById(Id).className='Expanded';\r\n" +
                    "     }\r\n" +
                    "     else\r\n" +
                    "     {\r\n" +
                    "         document.getElementById(Id).className='Collapsed';\r\n" +
                    "     }\r\n" +
                    "  }\r\n" +

                     " function CallSaveCmsData(CloseWindow)\r\n" +
                     " {\r\n" +
                     "      document.getElementById('divCallSaveAddDataProcessing').innerHTML='Tiến hành cập nhật và đánh index tìm kiếm...';\r\n" +
                     "      setTimeout('RealCallSaveCmsData('+CloseWindow+')',10);\r\n" +
                     " }\r\n" +

                     "  function RealCallSaveCmsData(CloseWindow)\r\n" +
                     "  {\r\n" +                     
                     "      SiteId='" + SiteId + "';\r\n" +
                     "      GroupDataId='" + GroupDataId + "';\r\n" +
                     "      DataId=document.getElementById('txtDataId').value;\r\n" +
                     "      Alias = document.getElementById('txtAlias').value;\r\n" +
                     "      Subject = document.getElementById('txtSubject').value;\r\n" +
                     
                     "      Description = '';//document.getElementById('txtDescription').value;\r\n" +
                     "      DocType='';\r\n" +
                     "      if(document.getElementById('drpSelectDocType')!=null)\r\n" +
                     "      {\r\n" +
                     "          DocType=document.getElementById('drpSelectDocType').value;\r\n" +
                     "      }\r\n" +

                     "      DocField='';\r\n" +
                     "      if(document.getElementById('drpSelectDocField')!=null)\r\n" +
                     "      {\r\n" +
                     "          DocField=document.getElementById('drpSelectDocField').value;\r\n" +
                     "      }\r\n" +

                     "      DocReleaseFrom='';\r\n" +
                     "      if(document.getElementById('drpSelectDocReleaseFrom')!=null)\r\n" +
                     "      {\r\n" +
                     "          DocReleaseFrom=document.getElementById('drpSelectDocReleaseFrom').value;\r\n" +
                     "      }\r\n" +
                     "      DocSigner='';\r\n" +
                     "      if(document.getElementById('drpSelectDocSigner')!=null)\r\n" +
                     "      {\r\n" +
                     "          DocSigner=document.getElementById('drpSelectDocSigner').value;\r\n" +
                     "      }\r\n" +

                     "      DocStatus='';\r\n" +
                     "      if(document.getElementById('drpSelectDocStatus')!=null)\r\n" +
                     "      {\r\n" +
                     "          DocStatus=document.getElementById('drpSelectDocStatus').value;\r\n" +
                     "      }\r\n" +

                     "      ReleaseDate='';\r\n" +
                     "      if(document.getElementById('txtReleaseDate')!=null)\r\n" +
                     "      {\r\n" +
                     "          ReleaseDate=document.getElementById('txtReleaseDate').value;\r\n" +
                     "      }\r\n" +

                     "      EffectedDate='';\r\n" +
                     "      if(document.getElementById('txtEffectedDate')!=null)\r\n" +
                     "      {\r\n" +
                     "          EffectedDate=document.getElementById('txtEffectedDate').value;\r\n" +
                     "      }\r\n" +

                     "      EndEffectedDate='';\r\n" +
                     "      if(document.getElementById('txtEndEffectedDate')!=null)\r\n" +
                     "      {\r\n" +
                     "          EndEffectedDate=document.getElementById('txtEndEffectedDate').value;\r\n" +
                     "      }\r\n" +

                     "      SignDate='';\r\n" +
                     "      if(document.getElementById('txtSignDate')!=null)\r\n" +
                     "      {\r\n" +
                     "          SignDate=document.getElementById('txtSignDate').value;\r\n" +
                     "      }\r\n" +

                     "      ReplaceDoc='';\r\n" +
                     "      if(document.getElementById('txtReplaceDoc')!=null)\r\n" +
                     "      {\r\n" +
                     "          ReplaceDoc=document.getElementById('txtReplaceDoc').value;\r\n" +
                     "      }\r\n" +

                     "      ModifyDoc='';\r\n" +
                     "      if(document.getElementById('txtModifyDoc')!=null)\r\n" +
                     "      {\r\n" +
                     "          ModifyDoc=document.getElementById('txtModifyDoc').value;\r\n" +
                     "      }\r\n" +

                     "      IsNew = document.getElementById('drpSelectIsNew').value;\r\n" +
                     "      Searchable=0;\r\n" +
                     "      if(document.getElementById('drpSelectSearchable')!=null)\r\n" +
                     "      {\r\n" +
                     "          Searchable=document.getElementById('drpSelectSearchable').value;\r\n" +
                     "      }\r\n" +

                     "      UploadFile=document.getElementById('txtUploadFile').value;\r\n" +                     
                     "      var startIndex = document.getElementById('hdRelationTypeDocStart').value;\r\n" +
                     "      var endIndex = document.getElementById('hdRelationTypeDocEnd').value;\r\n" +
                     "      var arr = []; \r\n" +
                     "      for(var index = startIndex; index < endIndex; index++) { \r\n" +
                     "          arr.push(document.getElementById('txtRelationTypeText_'+index).value);// + '_X_';  \r\n" +
                     "      } \r\n" +                     
                     
                     "      AjaxOut = Portal.Cms.Render.UpdateCmsDocumentDataRenderBll.ServerSideSave(SiteId, GroupDataId, DataId, Alias, Subject, Description, UploadFile, DocType,DocField, DocReleaseFrom,DocSigner,DocStatus,SignDate, ReleaseDate,EffectedDate,EndEffectedDate,ReplaceDoc,ModifyDoc, IsNew,Searchable,arr).value;\r\n" +                   
                     "      document.getElementById('divCallSaveAddDataProcessing').innerHTML='';\r\n" +
                     "      if(AjaxOut.Error)\r\n" +
                     "      {\r\n" +
                     "          alert(AjaxOut.InfoMessage);\r\n" +
                     "          return;\r\n" +
                     "      }\r\n" +
                     "      if(CloseWindow==1)\r\n" +
                     "      {\r\n" +
                     "          window.open('" + BackUrl + "','_self');\r\n" +
                     "      }\r\n" +
                     "      else\r\n" +
                     "      {\r\n" +
                     "          if(AjaxOut.RetUrl!='')\r\n" +
                     "          {\r\n" +
                     "              window.open(AjaxOut.RetUrl,'_self');\r\n" +
                     "          }\r\n" +
                     "      }\r\n" +
                     "  }\r\n" +


                    "   function ClientAddRelationDocument(GroupDataId,DataId,RelationTypeId)\r\n" +
                    "   {\r\n" +
                    "       SiteId='" + SiteId + "';\r\n" +
                    "       documentNo=document.getElementById('txtRelationTypeText'+RelationTypeId).value;\r\n" +
                    "       documentNo=documentNo.trim();\r\n" +
                    "       if(documentNo=='')\r\n" +
                    "       {\r\n" +
                    "           alert('Chưa nhập số văn bản liên quan!');\r\n" +
                    "           document.getElementById('txtRelationTypeText'+RelationTypeId).focus();\r\n" +
                    "           return;\r\n" +
                    "       }\r\n" +
                    "       AjaxOut = Portal.Cms.Render.UpdateCmsDocumentDataRenderBll.ServerSideAddRelationDocument(SiteId,GroupDataId, DataId, RelationTypeId, documentNo, '" + BackUrl + "').value;\r\n" +
                    "       if(AjaxOut.Error)\r\n" +
                    "       {\r\n" +
                    "           alert(AjaxOut.InfoMessage);\r\n" +
                    "           return;\r\n" +
                    "       }\r\n" +
                    "       window.open(AjaxOut.RetUrl,'_self');\r\n" +
                    "   }\r\n" +

                    "   function ClientDeleteRelation(RelationDataId,GroupDataId,DataId,RelationTypeId)\r\n" +
                    "   {\r\n" +
                    "       SiteId='" + SiteId + "';\r\n" +
                    "       if(confirm('Bạn đã chắc chắn xóa chưa?')==false)return;\r\n" +
                    "       AjaxOut = Portal.Cms.Render.UpdateCmsDocumentDataRenderBll.ServerSideDeleteRelationDocument(SiteId,RelationDataId, GroupDataId, DataId, RelationTypeId, '" + BackUrl + "').value;\r\n" +
                    "       if(AjaxOut.Error)\r\n" +
                    "       {\r\n" +
                    "           alert(AjaxOut.InfoMessage);\r\n" +
                    "           return;\r\n" +
                    "       }\r\n" +
                    "       window.open(AjaxOut.RetUrl,'_self');\r\n" +
                    "   }\r\n" +


                    //upload file
                     "function fileSelected() {\r\n" +
                     "    var file = document.getElementById('fileToUpload').files[0];\r\n" +
                     "    if (file) {\r\n" +
                      "        var ext = file.name.split('.').pop();" +
                     "        if(ext=='PDF'||ext=='pdf'||ext=='docx'||ext=='doc') \r\n" +
                     "        {\r\n" +
                     "        var fileSize = 0;\r\n" +
                     "        if (file.size > 1024 * 1024)\r\n" +
                     "            fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';\r\n" +
                     "        else\r\n" +
                     "            fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';\r\n" +
                     "        document.getElementById('fileName').innerHTML = 'Tên tệp: ' + file.name;\r\n" +
                     "        document.getElementById('fileSize').innerHTML = 'Kích cỡ: ' + fileSize;\r\n" +
                     "        document.getElementById('fileType').innerHTML = 'Loại tệp: ' + file.type;\r\n" +
                     ////Bo doan nay
                     "    var fd = new FormData();\r\n" +
                     "    fd.append(\"fileToUpload\", document.getElementById('fileToUpload').files[0]);\r\n" +
                     "    var xhr = new XMLHttpRequest();\r\n" +
                     "    xhr.upload.addEventListener(\"progress\", uploadProgress, false);\r\n" +
                     "    xhr.addEventListener(\"load\", uploadCompletePreview, false);\r\n" +
                    //"    xhr.addEventListener(\"error\", uploadFailed, false);\r\n" +
                    //"    xhr.addEventListener(\"abort\", uploadCanceled, false);\r\n" +
                     "    xhr.open(\"POST\", \"" + UploadHandler + "?sid=" + SiteId + "\");\r\n" +
                     "    xhr.send(fd);\r\n" +
                    // "        document.getElementById('fileImageUrl').innerHTML = '<img src='+file.fileName+'>';\r\n" +
                    ///End
                      "        }\r\n" +
                    "        else {\r\n" +
                    "           alert('Hệ thống chỉ chấp nhận file đính kèm là Word và Pdf!'); \r\n" +
                    "           return; \r\n" +
                    "        }\r\n" +
                     "    }\r\n" +
                     "}\r\n" +

                     "function uploadFile() {\r\n" +

                      "    if(document.getElementById('fileToUpload').value==''){\r\n" +
                    //"        CallSaveAddData();\r\n" +
                     "       CallSaveCmsData(1);\r\n" +
                     "       return;\r\n" +
                     "     }\r\n" +
                     "    DataId=document.getElementById('txtDataId').value;\r\n" +
                     "    var file = document.getElementById('fileToUpload').files[0];\r\n" +

                     "    if (file) {\r\n" +
                     "        var ext = file.name.split('.').pop();" +
                     "        if(ext=='PDF'||ext=='pdf'||ext=='docx'||ext=='doc') \r\n" +
                     "        {\r\n" +
                     "    var fd = new FormData();\r\n" +
                     "    fd.append(\"fileToUpload\", document.getElementById('fileToUpload').files[0]);\r\n" +
                     "    var xhr = new XMLHttpRequest();\r\n" +
                     "    xhr.upload.addEventListener(\"progress\", uploadProgress, false);\r\n" +
                     "    xhr.addEventListener(\"load\", uploadComplete, false);\r\n" +
                     "    xhr.addEventListener(\"error\", uploadFailed, false);\r\n" +
                     "    xhr.addEventListener(\"abort\", uploadCanceled, false);\r\n" +
                     "    xhr.open(\"POST\", \"" + UploadHandler + "?sid=" + SiteId + "&uni=" + WebSessionUtility.GetCurrentLoginUser().AssetCode + "&gid=" + GroupDataId + "&dataid=" + CmsDataId + "\");\r\n" +
                     "    xhr.send(fd);\r\n" +
                       "          }\r\n" +
                     "        else {\r\n" +
                     "           alert('Hệ thống chỉ chấp nhận file đính kèm là Word và Pdf!'); \r\n" +
                     "           return; \r\n" +
                     "        }\r\n" +
                     " }\r\n" +
                     "}\r\n" +

                     "function uploadProgress(evt) {\r\n" +
                     "    if (evt.lengthComputable) {\r\n" +
                     "    }\r\n" +
                     "    else {\r\n" +
                     "        document.getElementById('progressNumber').innerHTML = 'Không tính toán được thời gian';\r\n" +
                     "    }\r\n" +
                     "}\r\n" +


                     "function uploadCompletePreview(evt) {\r\n" +
                    //"        document.getElementById('fileImageUrl').innerHTML = evt.target.responseText;\r\n" +
                     "}\r\n" +


                     "function uploadComplete(evt) {\r\n" +
                     "    /* This event is raised when the server send back a response */\r\n" +
                     "  if(evt.target.responseText.indexOf('ERROR')!=-1)\r\n" +
                     "  {\r\n" +
                     "      alert(evt.target.responseText.substring(6));\r\n" +
                     "      return;\r\n" +
                     "  }\r\n" +
                     "    document.getElementById('txtUploadFile').value=evt.target.responseText;\r\n" +                     
                     "    //doan nay chay upload vao day...\r\n" +
                     "    CallSaveCmsData(1);\r\n" +
                     "   }\r\n" +

                       "function uploadFailed(evt) {\r\n" +
                     "       alert(\"Lỗi khi tải tệp dữ liệu lên máy chủ.\");\r\n" +
                     "   }\r\n" +

                     "   function uploadCanceled(evt) {\r\n" +
                     "        alert(\"Người dùng hủy bỏ tải lên máy chủ hoặc mất kết nối với máy chủ.\");\r\n" +
                     "   }\r\n" +
                    //end upoad file

                     "  </script>\r\n";



                string SelectIsNew =
                     " <select id=\"drpSelectIsNew\">\r\n" +
                     "      <option value=\"0\">Tài liệu bình thường</option>\r\n" +
                     "      <option value=\"1\" selected>Tài liệu mới</option>\r\n" +
                     " </select>\r\n";
                if (OCmsData.IsNew == 1)
                {
                    SelectIsNew =
                        " <select id=\"drpSelectIsNew\">\r\n" +
                        "      <option value=\"0\">Tài liệu bình thường</option>\r\n" +
                        "      <option selected value=\"1\" selected>Tài liệu mới</option>\r\n" +
                        " </select>\r\n";
                }

                string SelectSearchable =
                    " <select id=\"drpSelectSearchable\">\r\n" +
                    "      <option value=\"0\">Không tìm kiếm toàn văn được</option>\r\n" +
                    "      <option value=\"1\" selected>Tìm kiếm toàn văn được</option>\r\n" +
                    " </select>\r\n";
                if (OCmsData.AttachedSearchable == 1)
                {
                    SelectSearchable =
                    " <select id=\"drpSelectSearchable\">\r\n" +
                    "      <option value=\"0\">Không tìm kiếm toàn văn được</option>\r\n" +
                    "      <option selected value=\"1\" selected>Tìm kiếm toàn văn được</option>\r\n" +
                    " </select>\r\n";
                }
                string ButtonRoot = WebConfig.GetButtonIconRoot(OSiteParam);
                Html +=
                   " <input id=txtCheckedCategory type=hidden value=\"" + OCmsData.CategoryIds + "\">\r\n" +
                   " <input id=txtCheckedHotCategory type=hidden value=\"" + OCmsData.HotCategoryIds + "\">\r\n" +
                   " <div class=DatabaseFunction>\r\n" +
                   "        <ul>\r\n" +
                   //"            <li onclick=\"javascript:CallSaveCmsData(0);\"><img class=image src=\"" + ButtonRoot + "/Save.png\"><div>Ghi lại</div></li>\r\n" +
                   "            <li onclick=\"javascript:uploadFile();\"><img class=image src=\"" + ButtonRoot + "/Save.png\"><div>Ghi lại</div></li>\r\n" +
                   //"            <li onclick=\"javascript:CallSaveCmsData(1);\"><img class=image src=\"" + ButtonRoot + "/Save.png\"><div>Ghi lại và đóng</div></li>\r\n" +
                   "            <li onclick=\"" + BackScript + "\"><img class=image src=\"" + ButtonRoot + "/back.png\"><div>Quay lại</div></li>\r\n" +
                   "        </ul>\r\n" +
                   "  </div>\r\n" +
                   "<div class=CssFormSaveUpdate>\r\n" +
                   "  <input type=hidden id=txtDataId value=\"" + CmsDataId + "\">\r\n" +
                   "  <div id=divCallSaveAddDataProcessing class=CssProcessing></div>\r\n" +
                   "  <table>\r\n" +
                   "    <tr class=\"CssRowAlias\">\r\n" +
                   "        <td class=c1>Số văn bản:" + Utility.fieldRequired + " </td>\r\n" +
                   "        <td class=c2><input id=txtAlias value=\"" + OCmsData.Subject + "\" class=textbox type=textbox></td>\r\n" +
                   "    </tr>\r\n" +
                   "    <tr class=\"CssRowSubject\">\r\n" +
                   "        <td class=c1>Trích yếu:" + Utility.fieldRequired + "</td>\r\n" +
                    //"        <td class=c2><input id=txtSubject class=textbox type=textbox value=\"" + OCmsData.Description + "\"></td>\r\n" +
                   "        <td class=c2><textarea type=textarea class=textarea id=\"txtSubject\" name=\"txtSubject\">" + OCmsData.Description + "</textarea></td>\r\n" +
                   "    </tr>\r\n";

                string SelectDocumentType =
                    "<select id=drpSelectDocType class=drplist>\r\n";
                DocTypeCls[] DocTypes = DocTypeProcessBll.ReadingDocType(SiteId, GroupDataId);
                for (int iIndex = 0; iIndex < DocTypes.Length; iIndex++)
                {
                    if (OCmsData.frkDocTypeId.Equals(DocTypes[iIndex].DocTypeId))
                    {
                        SelectDocumentType += "   <option selected value=\"" + DocTypes[iIndex].DocTypeId + "\">" + DocTypes[iIndex].DocTypeName + "</option>\r\n";
                    }
                    else
                    {
                        SelectDocumentType += "   <option value=\"" + DocTypes[iIndex].DocTypeId + "\">" + DocTypes[iIndex].DocTypeName + "</option>\r\n";
                    }
                }
                SelectDocumentType += "</select>\r\n";


                string SelectDocField =
                  "<select id=drpSelectDocField class=drplist>\r\n";
                DocFieldCls[] DocFields = DocFieldProcessBll.ReadingDocField(SiteId, GroupDataId);
                for (int iIndex = 0; iIndex < DocFields.Length; iIndex++)
                {
                    if (OCmsData.frkDocFieldId.Equals(DocFields[iIndex].DocFieldId))
                    {
                        SelectDocField += "   <option selected value=\"" + DocFields[iIndex].DocFieldId + "\">" + DocFields[iIndex].DocFieldName + "</option>\r\n";
                    }
                    else
                    {
                        SelectDocField += "   <option value=\"" + DocFields[iIndex].DocFieldId + "\">" + DocFields[iIndex].DocFieldName + "</option>\r\n";
                    }
                }
                SelectDocField += "</select>\r\n";

                StringBuilder SelectDocReleaseFrom = new StringBuilder();

                SelectDocReleaseFrom.Append(
                        "<select id=drpSelectDocReleaseFrom class=drplist>\r\n");

                DocReleaseFromCls[] DocReleaseFroms = DocReleaseFromProcessBll.ReadingDocReleaseFrom(SiteId, GroupDataId);
                for (int iIndex = 0; iIndex < DocReleaseFroms.Length; iIndex++)
                {
                    if (DocReleaseFroms[iIndex].DocReleaseFromId.Equals(OCmsData.frkDocReleaseFromId))
                    {
                        SelectDocReleaseFrom.Append("   <option selected value=\"" + DocReleaseFroms[iIndex].DocReleaseFromId + "\">" + DocReleaseFroms[iIndex].DocReleaseFromName + "</option>\r\n");
                    }
                    else
                    {
                        SelectDocReleaseFrom.Append("   <option value=\"" + DocReleaseFroms[iIndex].DocReleaseFromId + "\">" + DocReleaseFroms[iIndex].DocReleaseFromName + "</option>\r\n");
                    }
                }
                SelectDocReleaseFrom.Append("</select>\r\n");

                string SelectDocSigner =
                  "<select id=drpSelectDocSigner class=drplist>\r\n";
                DocSignerCls[] DocSigners = DocSignerProcessBll.ReadingDocSigner(SiteId, GroupDataId);
                for (int iIndex = 0; iIndex < DocSigners.Length; iIndex++)
                {
                    if (DocSigners[iIndex].DocSignerId.Equals(OCmsData.frkDocSignerId))
                    {
                        SelectDocSigner += "   <option selected value=\"" + DocSigners[iIndex].DocSignerId + "\">" + DocSigners[iIndex].DocSignerName + "</option>\r\n";
                    }
                    else
                    {
                        SelectDocSigner += "   <option value=\"" + DocSigners[iIndex].DocSignerId + "\">" + DocSigners[iIndex].DocSignerName + "</option>\r\n";
                    }
                }
                SelectDocSigner += "</select>\r\n";

                string SelectStatus = string.Empty;

                if (OCmsData.DocStatus.Equals("1"))
                {
                    SelectStatus =
                    "<select id=drpSelectDocStatus class=drplist>\r\n" +
                    "   <option value=\"0\">Hết hiệu lực</option>\r\n" +
                    "   <option selected=\"selected\" value=\"1\">Có hiệu lực</option>\r\n" +
                    "</select>\r\n";
                }
                else
                {
                    SelectStatus =
                    "<select id=drpSelectDocStatus class=drplist>\r\n" +
                    "   <option selected=\"selected\" value=\"0\">Hết hiệu lực</option>\r\n" +
                    "   <option value=\"1\">Có hiệu lực</option>\r\n" +
                    "</select>\r\n";
                }


                Html +=
                 "    <tr>\r\n" +
                 "        <td class=c1>Loại văn bản:" + Utility.fieldRequired + "</td>\r\n" +
                 "        <td class=c2>" + SelectDocumentType + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Cơ quan ban hành:" + Utility.fieldRequired + "</td>\r\n" +
                 "        <td class=c2>" + SelectDocReleaseFrom + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Lĩnh vực:" + Utility.fieldRequired + "</td>\r\n" +
                 "        <td class=c2>" + SelectDocField + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Người ký:" + Utility.fieldRequired + "</td>\r\n" +
                 "        <td class=c2>" + SelectDocSigner + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Trạng thái:" + Utility.fieldRequired + "</td>\r\n" +
                 "        <td class=c2>" + SelectStatus + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Ngày ban hành:" + Utility.fieldRequired + "</td>\r\n" +
                 "        <td class=c2>" + LookUpUtilities.GenerateLookUpDate("txtReleaseDate", OCmsData.ReleaseDate) + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Ngày hiệu lực:</td>\r\n" +
                 "        <td class=c2>" + LookUpUtilities.GenerateLookUpDate("txtEffectedDate", OCmsData.EffectedDate) + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Ngày đăng công báo:</td>\r\n" +
                 "        <td class=c2>" + LookUpUtilities.GenerateLookUpDate("txtSignDate", OCmsData.SignDate) + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Ngày hết hiệu lực:</td>\r\n" +
                 "        <td class=c2>" + LookUpUtilities.GenerateLookUpDate("txtEndEffectedDate", OCmsData.EndEffectedDate) + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr >\r\n" +
                 "        <td class=c1>Tìm kiếm toàn văn:</td>\r\n" +
                 "        <td class=c2>" + SelectSearchable + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "    <tr>\r\n" +
                 "        <td class=c1>Tài liệu đính kèm:</td>\r\n" +
                 "        <td class=c2><a href=\"#\" onclick=\"window.open('" + OCmsData.GetAttachDocUrl(SiteId, WebConfig.HttpDataRoot(OSiteParam)) + "','_blank'); \">Xem tài liệu</td>\r\n" +
                 "    </tr>\r\n" +

                 "    <tr class=\"CssRowAttachFile\">\r\n" +
                 "         <td class=c1>Cập nhật tài liệu gắn kèm:</td>\r\n" +
                 "         <td><input type=hidden id=\"txtUploadFile\"><input type=\"file\" name=\"fileToUpload[]\" id=\"fileToUpload\" onchange=\"fileSelected();\" /></td>\r\n" +
                 "       </tr>\r\n" +

                 "    </tr>\r\n" +
                 "       <tr>\r\n" +
                "           <td></td>\r\n" +
                "           <td>\r\n" +
                "               <div id=\"progressNumber\"></div>\r\n" +
                "               <div id=\"fileName\">\r\n" +
                "               </div>\r\n" +
                "               <div id=\"fileSize\">\r\n" +
                "               </div>\r\n" +
                "               <div id=\"fileType\">\r\n" +
                "               </div>\r\n" +
                "               <div id=fileImageUrl></div>\r\n" +
                "           </td>\r\n" +
                 "       <tr>\r\n" +
                 "    <tr class=\"CssRowStatus\">\r\n" +
                 "        <td class=c1>Trạng thái:</td>\r\n" +
                 "        <td class=c2>" + SelectIsNew + "</td>\r\n" +
                 "    </tr>\r\n" +
                 "  </table>\r\n" +
                 "</div>\r\n";


                bool AllowManage = true;// SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, GroupDataPermission.StaticId, GroupDataPermission.funcManage, gid, WebSessionUtility.GetCurrentLoginUser().UserId, false);
                if (AllowManage)
                {
                    Html += "<div class='RelationDivFunc'>";
                    RelationTypeCls[] RelationTypes = RelationTypeProcessBll.ReadingRelationType(SiteId, OCmsData.frkGroupDataId);

                    for (int iIndex = 0; iIndex < RelationTypes.Length; iIndex++)
                    {
                        CmsDataRelationCls[] CmsDataRelations = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).ReadingDocumentRelation(SiteId, OCmsData.DataId, RelationTypes[iIndex].RelationTypeId);
                        Html +=
                        " <h3>" + RelationTypes[iIndex].RelationTypeName + "</h3>\r\n" +
                        " <div class=CssRelationDivFunc>Số văn bản: <input type=textbox id=\"txtRelationTypeText_" + RelationTypes[iIndex].SortIndex + "\" class=textbox> \r\n";                        
                        if (iIndex == 0)
                            Html += "     <input type=hidden id=\"hdRelationTypeDocStart\" value=\"" + RelationTypes[iIndex].SortIndex + "\"> ";
                        if (iIndex == RelationTypes.Length - 1)
                            Html += "     <input type=hidden id=\"hdRelationTypeDocEnd\" value=\"" + RelationTypes[iIndex].SortIndex + "\"> ";

                        Html +=
                        "</div>\r\n" +
                        " <div class=relationdoc>\r\n" +
                        " <ul>\r\n";
                        for (int zIndex = 0; zIndex < CmsDataRelations.Length; zIndex++)
                        {
                            Html +=
                                "<li>\r\n" +
                                "   <img class=\"imgdelete\" onclick=\"javascript:ClientDeleteRelation('" + CmsDataRelations[zIndex].RelationDataId + "','" + OCmsData.frkGroupDataId + "','" + OCmsData.DataId + "','" + RelationTypes[iIndex].RelationTypeId + "');\" src=\"" + ButtonRoot + "/delete.png\"> <a href=\"PreviewCmsDocumentData.aspx?gid=" + GroupDataId + "&CmsDataId=" + CmsDataRelations[zIndex].DataId + "\" target=\"_blank\"> Số văn bản: <span class=DocNo>" + CmsDataRelations[zIndex].Subject + "</span></a>\r\n" +
                                "</li>\r\n";
                        }
                        Html +=
                        "</ul>\r\n" +
                        "</div>\r\n";
                    }
                    Html += "</div>";
                }
                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.Error = true;
            }

            return OAjaxOut;
        }


        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideSave(
            string SiteId,
            string GroupDataId,
            string DataId,
            string Alias,
            string Subject,
            string Description,
            string UploadFile,
            string DocType,
            string DocField,
            string DocReleaseFrom,
            string DocSigner,
            string DocStatus,
            string SignDate,
            string ReleaseDate,
            string EffectedDate,
            string EndEffectedDate,
            string ReplaceDoc,
            string ModifyDoc,
            int IsNew,
            int AttachedSearchable,
            string[] arrRelationDocType)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                if (string.IsNullOrEmpty(Subject)) throw new Exception("Chưa nhập trích yếu!");
                if (!string.IsNullOrEmpty(ReleaseDate))
                {
                    if (FunctionUtilities.checkVnDate(ReleaseDate) == false) throw new Exception("Ngày ban hành không hợp lệ!");
                }
                if (!string.IsNullOrEmpty(EffectedDate))
                {
                    if (FunctionUtilities.checkVnDate(EffectedDate) == false) throw new Exception("Ngày hiệu lực không hợp lệ!");
                }

                //ServerSideAddRelationDocument(SiteId,GroupDataId,DataId, string.Empty,

                CmsDataCls OCmsData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateCmsDataModel(null, SiteId, DataId);
                OCmsData.DataAlias = Alias;
                OCmsData.Subject = Alias;
                OCmsData.OtherSubject = "";
                OCmsData.Description = Subject;
                OCmsData.Body = "";
                OCmsData.Source = "";
                OCmsData.Url = "";
                OCmsData.Target = "_self";

                if (!string.IsNullOrEmpty(UploadFile))
                    OCmsData.UploadFile = UploadFile;

                OCmsData.SortIndex = 0;
                OCmsData.frkDocTypeId = DocType;
                OCmsData.frkDocFieldId = DocField;
                OCmsData.frkDocReleaseFromId = DocReleaseFrom;
                OCmsData.frkDocSignerId = DocSigner;
                OCmsData.DocStatus = DocStatus;
                OCmsData.SignDate = SignDate;
                OCmsData.ReleaseDate = ReleaseDate;
                OCmsData.EffectedDate = EffectedDate;
                OCmsData.EndEffectedDate = EndEffectedDate;
                OCmsData.ReplaceDoc = ReplaceDoc;
                OCmsData.ModifyDoc = ModifyDoc;
                OCmsData.IsNew = IsNew;
                OCmsData.AttachedSearchable = AttachedSearchable;

                ///Luu cap nhat
                CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).SaveCmsData(null, SiteId, DataId, OCmsData, true);
                ///Luu van ban lien quan
                ServerSideAddRelationList(SiteId, GroupDataId, DataId, arrRelationDocType, string.Empty);
                
                OAjaxOut.RetUrl = "DocumentInputData.aspx?gid=" + GroupDataId;
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.Error = true;
            }

            return OAjaxOut;
        }


        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideAddRelationDocument(
            string SiteId,
            string GroupDataId,
            string SrcDataId,
            string RelationTypeId,
            string documentNo,
            string BackAspx)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                CmsDataCls OCmsData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateCmsDataModel(null, SiteId, documentNo);
                if (OCmsData == null)
                {
                    throw new Exception("Số văn bản liên quan không hợp lệ! Không tìm thấy số văn bản này!");
                }
                if (OCmsData.Equals(SrcDataId))
                {
                    throw new Exception("Số văn bản liên quan không hợp lệ! Văn bản liên quan không thể chính là văn bản này!");
                }
                CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).AddDocumentRelation(SiteId, SrcDataId, OCmsData.DataId, RelationTypeId);
                OAjaxOut.RetUrl = "?gid=" + GroupDataId + "&CmsDataId=" + SrcDataId + "&back=" + BackAspx;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }
            return OAjaxOut;
        }
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideAddRelationList(
            string SiteId,
            string GroupDataId,
            string SrcDataId,
            //string RelationTypeId,
            string[] documentNo,
            string BackAspx)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                CmsDataCls OCmsData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateCmsDataModel(null, SiteId, SrcDataId);
                if (OCmsData == null)
                {
                    throw new Exception("Số văn bản liên quan không hợp lệ! Không tìm thấy số văn bản này!");
                }               

                CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).AddDocumentRelationList(SiteId, SrcDataId, documentNo);
                OAjaxOut.RetUrl = "?gid=" + GroupDataId + "&CmsDataId=" + SrcDataId + "&back=" + BackAspx;

            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }
            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideDeleteRelationDocument(
            string SiteId,
            string RelationDataId,
            string GroupDataId,
            string SrcDataId,
            string RelationTypeId,
            string BackAspx)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).DeleteDocumentRelation(SiteId, RelationDataId);
                OAjaxOut.RetUrl = "?gid=" + GroupDataId + "&CmsDataId=" + SrcDataId + "&back=" + BackAspx;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }
            return OAjaxOut;
        }
    }
}
